{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3625677b-2e3b-4069-ac6b-ce6efbc7e70c",
   "metadata": {},
   "source": [
    "### How Do We Interface With External Resources?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c88048a6-f52c-4571-bf11-583aa2c30634",
   "metadata": {
    "height": 149
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Why did the database administrator leave his wife?\n",
      "She had one-to-many relationships.\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "url = \"https://v2.jokeapi.dev/joke/Any?safe-mode&type=twopart\"\n",
    "\n",
    "response = requests.get(url)\n",
    "\n",
    "print(response.json()[\"setup\"])\n",
    "print(response.json()[\"delivery\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4337dfaa-ed8b-4e8a-a1ae-2a117593a70e",
   "metadata": {
    "height": 30
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'error': False,\n",
       " 'category': 'Programming',\n",
       " 'type': 'twopart',\n",
       " 'setup': 'Why did the database administrator leave his wife?',\n",
       " 'delivery': 'She had one-to-many relationships.',\n",
       " 'flags': {'nsfw': False,\n",
       "  'religious': False,\n",
       "  'political': False,\n",
       "  'racist': False,\n",
       "  'sexist': False,\n",
       "  'explicit': False},\n",
       " 'safe': True,\n",
       " 'id': 265,\n",
       " 'lang': 'en'}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "11576230-09a6-471f-ae03-7dfd53f81a24",
   "metadata": {
    "height": 183
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "def give_joke(category : str):\n",
    "    \"\"\"\n",
    "    Joke categories. Supports: Any, Misc, Programming, Pun, Spooky, Christmas.\n",
    "    \"\"\"\n",
    "\n",
    "    url = f\"https://v2.jokeapi.dev/joke/{category}?safe-mode&type=twopart\"\n",
    "    response = requests.get(url)\n",
    "    print(response.json()[\"setup\"])\n",
    "    print(response.json()[\"delivery\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "dc480ae7-2f6e-4796-a4ca-f5d304081797",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "USER_QUERY = \"Hey! Can you get me a joke for this december?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "789b8c6d-7baa-419a-ae28-1538d7e9ccab",
   "metadata": {
    "height": 217
   },
   "outputs": [],
   "source": [
    "from utils import query_raven\n",
    "\n",
    "raven_functions = \\\n",
    "f'''\n",
    "def give_joke(category : str):\n",
    "    \"\"\"\n",
    "    Joke categories. Supports: Any, Misc, Programming, Dark, Pun, Spooky, Christmas.\n",
    "    \"\"\"\n",
    "\n",
    "User Query: {USER_QUERY}<human_end>\n",
    "'''\n",
    "call = query_raven(raven_functions)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "650051c1-148f-4b5a-95e4-b3b6dbaad4c4",
   "metadata": {
    "height": 30
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "What says Oh Oh Oh?\n",
      "Santa walking backwards!\n"
     ]
    }
   ],
   "source": [
    "exec(call)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "170eedef-330d-4466-93b5-aaf53e09f9d1",
   "metadata": {},
   "source": [
    "#### Writing A Tool That Uses OpenAPI APIs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "de0ffc0b-84a9-4622-ac37-976d7c1cdacc",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "#!wget https://raw.githubusercontent.com/open-meteo/open-meteo/main/openapi.yml"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c9105806-39ca-49c4-a930-993db2b3a820",
   "metadata": {
    "height": 251
   },
   "outputs": [],
   "source": [
    "import yaml\n",
    "import json\n",
    "\n",
    "# Read the content of the file\n",
    "with open('openapi.yml', 'r') as file:\n",
    "    file_content = file.read()\n",
    "file_content = file_content.replace(\"int\\n\", \"number\\n\")\n",
    "file_content = file_content.replace(\"float\\n\", \"number\\n\")\n",
    "data = yaml.safe_load(file_content)\n",
    "\n",
    "data[\"servers\"] = [{\"url\":\"https://api.open-meteo.com\"}]\n",
    "\n",
    "with open('openapi.json', 'w') as file:\n",
    "    json_content = json.dump(data, file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "1003872b-ed4c-4ce5-ba19-dbaad3d9d5df",
   "metadata": {
    "height": 30
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generating data from openapi.json\r\n"
     ]
    }
   ],
   "source": [
    "!openapi-python-generator openapi.json ./api_specification_main/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "df4400f9-803b-44ff-9e2b-738bf88e882f",
   "metadata": {
    "height": 47
   },
   "outputs": [],
   "source": [
    "from api_specification_main.services.WeatherForecastAPIs_service\\\n",
    "    import get_v1forecast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "b0dea523-1b71-4642-a526-e4e88f416920",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "user_query = \"Hey how is the current weather and windspeed in New York?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "10fa052c-9d92-4d23-b907-5971c704f7c1",
   "metadata": {
    "height": 319
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Function:\n",
      "get_v1forecast(latitude: float, longitude: float, hourly: Optional[List[str]] = None, daily: Optional[List[str]] = None, current_weather: Optional[bool] = None, temperature_unit: Optional[str] = None, wind_speed_unit: Optional[str] = None, timeformat: Optional[str] = None, timezone: Optional[str] = None, past_days: Optional[int] = None, api_config_override: Optional[api_specification_main.api_config.APIConfig] = None) -> Dict[str, Any]\n",
      "\"\"\"\n",
      "Requires the latitude and longitude.\n",
      "Set current_weather to True to get the weather.\n",
      "Set hourly or daily based on preference.\n",
      "\"\"\"\n",
      "\n",
      "User Query: Hey how is the current weather and windspeed in New York?<human_end>\n"
     ]
    }
   ],
   "source": [
    "import inspect\n",
    "signature = inspect.signature(get_v1forecast)\n",
    "docstring = \\\n",
    "'''\n",
    "Requires the latitude and longitude.\n",
    "Set current_weather to True to get the weather.\n",
    "Set hourly or daily based on preference.\n",
    "'''\n",
    "\n",
    "raven_prompt = \\\n",
    "f'''\n",
    "Function:\n",
    "{get_v1forecast.__name__}{signature}\n",
    "\"\"\"{docstring}\"\"\"\n",
    "\n",
    "User Query: {user_query}<human_end>'''\n",
    "\n",
    "print (raven_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "d75de144-c242-4aac-ab1f-20ec4d635aa4",
   "metadata": {
    "height": 64
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "get_v1forecast(latitude=40.7128, longitude=-74.0060, current_weather=True)\n"
     ]
    }
   ],
   "source": [
    "from utils import query_raven\n",
    "call = query_raven(raven_prompt)\n",
    "print (call)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "bc42f650-182a-4e4c-8fc4-ac5ef291e9ea",
   "metadata": {
    "height": 30
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'latitude': 40.710335,\n",
       " 'longitude': -73.99307,\n",
       " 'generationtime_ms': 0.08893013000488281,\n",
       " 'utc_offset_seconds': 0,\n",
       " 'timezone': 'GMT',\n",
       " 'timezone_abbreviation': 'GMT',\n",
       " 'elevation': 32.0,\n",
       " 'current_weather_units': {'time': 'iso8601',\n",
       "  'interval': 'seconds',\n",
       "  'temperature': '°C',\n",
       "  'windspeed': 'km/h',\n",
       "  'winddirection': '°',\n",
       "  'is_day': '',\n",
       "  'weathercode': 'wmo code'},\n",
       " 'current_weather': {'time': '2024-06-25T16:15',\n",
       "  'interval': 900,\n",
       "  'temperature': 31.7,\n",
       "  'windspeed': 15.7,\n",
       "  'winddirection': 281,\n",
       "  'is_day': 1,\n",
       "  'weathercode': 0}}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "eval(call)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93317b06-c6dc-4214-8c94-b04536b02b4d",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
